package cn.wolfcode.luowowo.website.web.controller;

import cn.wolfcode.luowowo.cache.util.RedisKeysUtil;
import cn.wolfcode.luowowo.exception.LogicException;
import cn.wolfcode.luowowo.member.service.IUserInfoService;
import cn.wolfcode.luowowo.util.AjaxResult;
import cn.wolfcode.luowowo.website.util.ConstantUtil;
import cn.wolfcode.luowowo.website.util.CookieUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;

@Controller
public class LoginController {

    @Reference
    private IUserInfoService userInfoService;

    @RequestMapping("checkPhone")
    @ResponseBody
    public Object checkPhone(String phone) {
        try {
            return userInfoService.checkPhone(phone);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @RequestMapping("sendVerifyCode")
    @ResponseBody
    public AjaxResult sendVerifyCode(String phone) {
        try {
            userInfoService.sendVerifyCode(phone);
            return AjaxResult.SUCCESS;
        } catch (LogicException e) {
            e.printStackTrace();
            return new AjaxResult(false, e.getMessage());
        }
    }

    @RequestMapping("userRegist")
    @ResponseBody
    public AjaxResult userRegist(String phone, String password, String rpassword, String nickname, String verifyCode) {
        userInfoService.userRegist(phone, password, rpassword, nickname, verifyCode);
        return AjaxResult.SUCCESS;
    }

    @RequestMapping("userLogin")
    @ResponseBody
    public AjaxResult userLogin(String username, String password, HttpServletResponse response) {
        String token = userInfoService.userLogin(username, password);
        // 将 token添加到 cookie中,
        CookieUtil.addCookie(ConstantUtil.USER_INFO_TOKEN_COOKIE_NAME, token, RedisKeysUtil.USER_LOGIN_TOKEN.getTime().intValue(), response);
        return AjaxResult.SUCCESS;
    }
}
